import com.adobe.cairngorm.control.CairngormEventDispatcher;

import flash.events.*;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.net.URLRequest;

import mx.collections.ArrayCollection;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

import net.optix.ip.events.AddActionEvent;
import net.optix.ip.events.AddTradeMarkActionEvent;
import net.optix.ip.model.ModelLocator;
import net.optix.ip.vo.ActionVO;
            
            
[Bindable]
public var model:ModelLocator	=	ModelLocator.getInstance(); 
            
public var files:FileReferenceList	=	new FileReferenceList();
public var uploadRUL:URLRequest;
public var filesData:ArrayCollection	=	new ArrayCollection();
  
public function init():void
{
	model.bSubmit	=	true;
  	model.result	=	"";
 	model.close		=	"no";
}
  			
private function titleWindow_close(evt:CloseEvent):void 
{ 
	model.result	=	"";
  	model.bSubmit	=	true;
  	PopUpManager.removePopUp(this); 
}
            
           
            
private function selectHandler(event:Object):void
{
  	for(var i:int =0; i< files.fileList.length; i++)
	{
   		var f:FileReference	=	FileReference(files.fileList[i]);
            		
   		var obj:Object	=	new Object();
      	obj.fileName	=	f.name; 
     	obj.fileSize	=	f.size+"B";
      	obj.fileType	=	f.type;
      	obj.fileRefrence = f;
        obj.fileStatus	=	0;
        		
      	filesData.addItem(obj);
 	}
   	selectedFiles.validateNow();
}
            
private function chooseFile():void
{
  	var url:String	=	model.url+"/Invention/UploadAction/";
 	uploadRUL		=	new URLRequest(url);
  	files.addEventListener(Event.SELECT,selectHandler);
  	files.browse();
}
            
public function uploadHandler(event:MouseEvent):void
{
 	var file:FileReference;
  	for(var i:int = 0 ; i<filesData.length; i++)
   	{
     	file	=	FileReference(filesData[i].fileRefrence);
      	file.upload(uploadRUL);
      	filesData[i].fileStatus	=	1;
  	}
}
            
public function updateAction():void
{
  	model.bSubmit	=	false;
 	var vo:ActionVO	=	new ActionVO();
 	
 	vo.inventionID	=	model.currentTradeMark.tradeMarkID;
	vo.type			=	actionType.selectedIndex;
	vo.description	=	actionDescription.text;
    vo.cost			=	Number(actionCost.text);
    var fileNames:String	=	"";
	if(filesData != null)
	{
		for(var i:int=0; i<filesData.length; i++)
	  	{
	   		if(filesData[i].fileStatus	==	1)
	    	{
	    		fileNames	=	fileNames+"-"+filesData[i].fileName;
	    	}
	  	}
	}
	    

	vo.fileNames	=	fileNames;
	         	
	var event:AddTradeMarkActionEvent	=	new AddTradeMarkActionEvent(vo);
   	CairngormEventDispatcher.getInstance().dispatchEvent(event);
}